﻿using System.Diagnostics.Contracts;
using System.IO;
using System.Windows;
using System.Windows.Markup;

namespace Infrastructure.Helpers
{
    /// <summary>
    /// Utility class for direct Xaml and related operations
    /// </summary>
    public static class XamlHelper
    {
        /// <summary>
        /// Loads the specified Xaml file.
        /// </summary>
        /// <param name="path">The path to the file.</param>
        /// <returns></returns>
        public static DependencyObject Load(string path)
        {
            Contract.Requires(!string.IsNullOrEmpty(path));
            
            using (var xamlStream = new FileStream(path, FileMode.Open))
            {
                return (DependencyObject) XamlReader.Load(xamlStream);
            }
        }

        /// <summary>
        /// Sets the data context.
        /// </summary>
        /// <param name="dobj">The dependency object.</param>
        /// <param name="dataContext">The data context.</param>
        public static void SetDataContext(this DependencyObject dobj, object dataContext)
        {
            var element = dobj as FrameworkElement;
            if(element != null)
            {
                element.DataContext = dataContext;
            }
        }
    }
}